package Dungeoneering.api.methods;

import java.util.ArrayList;

import org.powerbot.game.api.methods.Game;
import org.powerbot.game.api.methods.interactive.Players;
import org.powerbot.game.api.methods.node.SceneEntities;
import org.powerbot.game.api.util.Filter;
import org.powerbot.game.api.wrappers.Tile;
import org.powerbot.game.api.wrappers.node.SceneObject;
import org.powerbot.game.api.wrappers.node.SceneObject$Type;

/**
 * an extention of Locations, so we can find Locations (objects) in a more efficient way
 * @author Nicolaas
 *
 */
public class Objects extends SceneEntities {
	
	/**
	 * finds a Location (object) with given type at given tile
	 * @param tile the tile we look for the object
	 * @param type the type of object you're looking for
	 * @return The top object on the provided tile; or null if none found.
	 */
	public static SceneObject getTopAt(final Tile tile, final SceneObject$Type type) {
		for (final SceneObject l : getLoaded(tile)) {
			if (l != null && l.getType() == type)
				return l;
		}
		return null;
	}
	
	/**
	 * finds a Location (object) at given tile
	 * @param tile the tile we look for the object
	 * @return The top RSObject on the provided tile; or null if none found.
	 */
	public static SceneObject getTopAt(final Tile tile) {
		SceneObject[] locs = getLoaded(tile);
		return locs.length > 0 ? locs[0] : null;
	}
	
	/**
	 * finds all the Locations (objects) within a given radius around you, that have to be accepted by the given filter
	 * @param range the radius at which we load
	 * @param filter the objects have to pass this filter to get returned
	 * @return an array of all the Locations within a given radius and accepted by the filter
	 */
	public static SceneObject[] getLoadedLocations(final int range, final Filter<SceneObject> filter) {
		final ArrayList<SceneObject> objects = new ArrayList<SceneObject>();
		final int pX = Players.getLocal().getLocation().getX();
		final int pY = Players.getLocal().getLocation().getY();
		final int minX = pX - range, minY = pY - range;
		final int maxX = pX + range, maxY = pY + range;
		for (int x = minX; x < maxX; x++) {
			for (int y = minY; y < maxY; y++) {
				for (final SceneObject o : getLoaded(new Tile(x, y, Game.getPlane()))) {
					if (o != null && filter.accept(o)) {
						objects.add(o);
					}
				}
			}
		}
		return objects.toArray(new SceneObject[objects.size()]);
	}

}
